package com.axend.aerosense.dev.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.activity.DevBaseWifiActivity;
import com.axend.aerosense.dev.activity.NewDevSetNetActivity;
import com.axend.aerosense.dev.databinding.DevFragmentSearchBinding;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Add a New Device
 * 添加新设备界面
 */
public class DevSearchNetFragment extends MvvmBaseFragment<DevFragmentSearchBinding, ViewModel> {

    private LocationManager locationManager;
    private CustomTipsDialog tipsDialog;

    private List<String> permissionsList = new ArrayList<>();
    private RxPermissions rxPermissions;
    private Disposable disposable;
    private CustomTipsDialog enableGpsDialog;
    private CustomTipsDialog enableWifiDialog;
    private CustomTipsDialog enableBleDialog;

    public static DevSearchNetFragment getInstance(){
        DevSearchNetFragment fragment = new DevSearchNetFragment();
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        if(Build.VERSION.SDK_INT >= 33){
//            permissionsList.add(Manifest.permission.NEARBY_WIFI_DEVICES);
//        }else {
//            permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissionsList.add(Manifest.permission.BLUETOOTH_CONNECT);
            permissionsList.add(Manifest.permission.BLUETOOTH_SCAN);
            permissionsList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
        }

        rxPermissions = new RxPermissions(this);

        locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        if (null == locationManager && Build.VERSION.SDK_INT < 33) { LogUtils.d("该设备没有定位服务！"); }

        viewDataBinding.devNext.setOnClickListener(v->{
            //去下一个界面之前检查权限、wifi、蓝牙、定位开关
            if (!isGetPermissions()) {
                showTipsDialog();
                return;
            }

            if (!isEnableGPS() && Build.VERSION.SDK_INT < 33) {
                showEnableGpsDialog();
                return;
            }

            if (!isEnableWifi()) {
                showEnableWifiDialog();
                return;
            }

            if (!isEnableBle()) {
                showEnableBleDialog();
                return;
            }

            toNextPager();

        });

        //检查权限
        if (!isGetPermissions()) {
            showTipsDialog();
        }
    }

    /** 去下一个界面（设备选择界面） */
    private void toNextPager(){
        FragmentUtil.add(
                getActivity(),
                ((NewDevSetNetActivity)getActivity()).getContentId(),
                DevChooseDeviceFragment.getInstance(),
                this,
                true
        );
    }


    /** 显示申请权限的弹窗 */
    private void showTipsDialog(){
        if (null == tipsDialog) {
            tipsDialog = new CustomTipsDialog(getContext(), getString(R.string.dev_permission_tips));
            tipsDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    //确定
                    dismissTipsDialog();
                    getPermissions();
                }

                @Override
                public void onNegtiveClick() {
                    //取消
                    back();
                }
            });
        }
        tipsDialog.show();
    }

    /** 隐藏申请权限的弹窗 */
    private void dismissTipsDialog(){
        if (null == tipsDialog) { return; }
        tipsDialog.dismiss();
    }

    /** 显示打开GPS弹窗 */
    private void showEnableGpsDialog(){
        if (null == enableGpsDialog) {
            enableGpsDialog = new CustomTipsDialog(getContext(), getString(R.string.dev_open_gps_tip));
            enableGpsDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    dismissEnableGpsDialog();
                    //跳转到手机打开GPS页面
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    //设置完成后返回原来的界面
                    startActivity(intent);
                }

                @Override
                public void onNegtiveClick() {
                    dismissEnableGpsDialog();
                }
            });
        }
        enableGpsDialog.show();
    }

    /** 隐藏打开GPS弹窗 */
    private void dismissEnableGpsDialog(){
        if (null == enableGpsDialog) { return; }
        enableGpsDialog.dismiss();
    }

    /** 显示打开wifi提示弹窗 */
    private void showEnableWifiDialog(){
        if (null == enableWifiDialog) {
            enableWifiDialog = new CustomTipsDialog(getContext(), getString(R.string.dev_open_wifi_tips));
            enableWifiDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    dismissEnableWifiDialog();
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                }

                @Override
                public void onNegtiveClick() {
                    dismissEnableWifiDialog();
                }
            });
        }
        enableWifiDialog.show();
    }

    /** 隐藏打开wifi提示弹窗 */
    private void dismissEnableWifiDialog(){
        if (null == enableWifiDialog) {
            return;
        }
        enableWifiDialog.dismiss();
    }

    /** 显示开启蓝牙提示 */
    private void showEnableBleDialog(){
        if (null == enableBleDialog) {
            enableBleDialog = new CustomTipsDialog(getContext(), getString(R.string.dev_open_ble_tips));
            enableBleDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    dismissEnableBleDialog();
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                }

                @Override
                public void onNegtiveClick() {
                    dismissEnableBleDialog();
                }
            });
        }
        enableBleDialog.show();
    }

    /** 隐藏开启蓝牙提示 */
    private void dismissEnableBleDialog(){
        if (null == enableBleDialog) {
            return;
        }
        enableBleDialog.dismiss();
    }

    /** 是否打开GPS */
    private boolean isEnableGPS(){
        if (null == locationManager) {
            return false;
        }
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /** 是否打开wifi */
    private boolean isEnableWifi(){
        return getBaseActivity().isEnableWifi();
    }

    /** 是否打开蓝牙 */
    private boolean isEnableBle(){
        return getBaseActivity().isEnableBluetooth();
    }

    /**
     * 检查是否有权限
     * @return
     */
    private boolean isGetPermissions(){
        return PermissionUtils.isGranted(getPermissionsArr());
    }

    private String[] getPermissionsArr(){
        String[] arr = new String[]{};
        return permissionsList.toArray(arr);
    }

    private void getPermissions(){
        //申请定位权限
        disposable = rxPermissions.request(getPermissionsArr())
                .subscribe(aBoolean -> {

                }, throwable -> throwable.printStackTrace());
    }

    private void back(){
        //返回到上一个页面
        getActivity().onBackPressed();
    }

    private DevBaseWifiActivity getBaseActivity(){
        FragmentActivity activity = getActivity();
        if (activity instanceof DevBaseWifiActivity) {
            return (DevBaseWifiActivity) activity;
        }
        LogUtils.w("获取DevBaseWifiActivity失败！");
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        ((ITitle)getActivity()).setTitle(getString(R.string.dev_add_new));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissTipsDialog();
        dismissEnableWifiDialog();
        dismissEnableGpsDialog();
        dismissEnableBleDialog();
        if (null != disposable && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_search;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected ViewModel getViewModel() {
        return null;
    }

    @Override
    protected void onRetryBtnClick() {

    }
}